package com.jar.netty_demo.NIO;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * java NIO模型
 */
public class ChannelDemo {
    /**
     * 向文件中写入信息
     */
    @Test
    public void test1() throws IOException {
        String s = "hello 世界";
        FileOutputStream fileInputStream = new FileOutputStream("d://test.txt");
        //创建一个通道
        FileChannel channel = fileInputStream.getChannel();
        //创建一个缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //将数据放到缓冲区
        buffer.put(s.getBytes());

        buffer.flip();
        channel.write(buffer);
        fileInputStream.close();
    }

    /**
     * 读取文件信息
     */
    @Test
    public void test2() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("d://test.txt");

        FileChannel channel = fileInputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        channel.read(buffer);
        System.out.println(new String(buffer.array()));
    }

    /**
     * 复制文件
     */
    @Test
    public void test3() throws IOException {
        //读取流
        FileInputStream fileInputStream = new FileInputStream("test.txt");
        //写入流
        FileOutputStream fileOutputStream = new FileOutputStream("test2.txt");
        FileChannel channel1 = fileInputStream.getChannel();
        FileChannel channel2 = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        while (true) {
            //重置一下指针
            byteBuffer.clear();
            int read = channel1.read(byteBuffer);
            if (read == -1) {
                break;
            }
            //转换为读取
            byteBuffer.flip();
            channel2.write(byteBuffer);
            //读到缓冲区里
        }
        fileInputStream.close();
        fileOutputStream.close();
    }
}
